import Vue from 'vue';
// 身份证格式校验
export const checkIdCard = function(sIdCard) {
	//Wi 加权因子 Xi 余数0~10对应的校验码 Pi省份代码
	let Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
		Xi = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2],
		Pi = [11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51, 52, 53, 54,
			61, 62, 63, 64, 65, 71, 81, 82, 91
		],
		checkStatus = 0;
	// 检查身份证长度
	if(sIdCard.length == 18){
		checkStatus += 1;
	}
	//检验输入的省份编码是否有效
	if(checkStatus >= 1){
		let p2 = sIdCard.substr(0, 2);
		for (let i = 0; i < Pi.length; i++) {
			if (Pi[i] == p2) {
				checkStatus += 1;
			}
		}
	}
	//检验18位身份证号码出生日期是否有效
	//parseFloat过滤前导零，年份必需大于等于1900且小于等于当前年份，用Date()对象判断日期是否有效。
	if(checkStatus >= 2){
		 let year = parseFloat(sIdCard.substr(6, 4));
		 let month = parseFloat(sIdCard.substr(10, 2));
		 let day = parseFloat(sIdCard.substr(12, 2));
		 let checkDay = new Date(year, month - 1, day);
		 let nowDay = new Date();
		 if (1900 <= year && year <= nowDay.getFullYear() && month == (checkDay.getMonth() + 1) && day == checkDay
		 	.getDate()) {
		 	checkStatus += 1;
		 } 
	}
	//检验校验码是否有效  
	if(checkStatus >= 3){
		let aIdCard = sIdCard.split("");
		let sum = 0;
		for (let j = 0; j < Wi.length; j++) {
			sum += Wi[j] * aIdCard[j]; //线性加权求和  
		}
		let index = sum % 11; //求模，可能为0~10,可求对应的校验码是否于身份证的校验码匹配  
		if (Xi[index] == aIdCard[17].toUpperCase()) {
			checkStatus += 1;
		}
	}
	if (checkStatus == 4) {
		return true;
	} else {
		return false;
	}
};
/**
 * 时间转换为XX前
 */
export const clickDateDiff = function(value) {
	let dataValue = value;
	if (typeof value == "string") {
	  dataValue = new Date(value.replace(/-/g, "/")).getTime();
	}
	var result;
	var minute = 1000 * 60;
	var hour = minute * 60;
	var day = hour * 24;
	var month = day * 30;
	var now = new Date().getTime();
	var diffValue = parseInt(now) - parseInt(dataValue);
	if (diffValue < 0) {
	  return;
	}
	var monthC = diffValue / month;
	var weekC = diffValue / (7 * day);
	var dayC = diffValue / day;
	var hourC = diffValue / hour;
	var minC = diffValue / minute;
	if (monthC >= 1) {
	  result = "" + parseInt(monthC) + '月前';
	} else if (weekC >= 1) {
	  result = "" + parseInt(weekC) + '周前';
	} else if (dayC >= 1) {
	  result = "" + parseInt(dayC) + '天前';
	} else if (hourC >= 1) {
	  result = "" + parseInt(hourC) + '小时前';
	} else if (minC >= 1) {
	  result = "" + parseInt(minC) + '分钟前';
	} else {
	  result = '刚刚';
	}
	return result;
};
/**
 * 时间戳转换为想要的时间格式
 */
//时间戳转换为时间 format('yyyy-MM-dd hh:mm:ss')
//时间格式转换
Date.prototype.format = function(fmt = 'yyyy-MM-dd hh:mm:ss') { //author: meizz 
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
			"00" + o[
				k]).substr(("" + o[k]).length)));
	return fmt;
}
// 数据深拷贝
//使用方法 供新手参考 :
// 在vue文件中 import { cloneObj } from '@/js_sdk/common.js'
// let dataList = cloneObj(data)
const cloneObj = (obj) => {
	let newobj = obj.constructor === Array ? [] : {};
	if (typeof obj !== 'object') {
		return;
	}
	for (let i in obj) {
		newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
	}
	return newobj
};


/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const delayCall = (fn, t) => {
  const delay = t || 500
  let timer
  return function() {
    const args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fn.apply(this, args)
    }, delay)
  }
}
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
  let last
  let timer
  const interval = t || 500
  return function() {
    const args = arguments
    const now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}


//判断枚举对象取值
// 在vue文件中 import { enumeration } from '@/js_sdk/common.js'
// let valueStatus = enumeration(enumObj,0);
const enumeration = (enumObj, index) => {
	//enumObj ====> 枚举对象 例如：{0:"不通过",1:"通过",2:"待审批"};
	//index ====> 查询属性值或属性名
	for (let i in enumObj) {
		if (i == index) {
			return enumObj[i];
		} else if (enumObj[i] == index) {
			return i;
		}
	}
}

//本地缓存
const dataStroage = {
	//设置离线缓存
	setStroage: (key, data) => {
		uni.setStorageSync(key, data);
	},
	//获取离线缓存
	getStroage: (key) => {
		let data = uni.getStorageSync(key);
		return data;
	},
	//移除某个离线缓存
	removeStroage: (key) => {
		uni.removeStorageSync(key);
	},
	//移除所有离线缓存
	closeAllStroage: () => {
		uni.clearStorageSync();
	}
}

// 原生Js获取URL传递的参数
const getUrlParam = (name) => {
	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	let r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

//大于固定字符串显示省略号
const handleStr = (str,length) => {
	let handle_str;
	str.length <= length ? handle_str = str : handle_str = str.slice(0, length) + "...";
	return handle_str
}

/* 倒计时
  endtime 结束时间
  nowtime 开始时间 默认值时当前时间
*/
const countDown = (endtime,nowtime) => {
  let day = 0,
    hour = 0,
    minute = 0,
    second = 0, //时间默认值
    newtime = nowtime || new Date().valueOf()/1000,
    times = endtime - newtime;
  if (times > 0) {
    day = Math.floor(times / (60 * 60 * 24));
    hour = Math.floor(times / (60 * 60)) - (day * 24);
    minute = Math.floor(times / 60) - (day * 24 * 60) - (hour * 60);
    second = Math.floor(times) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
  }
  day <= 9 ? day = '0' + day : null;
  hour <= 9 ? hour = '0' + hour : null;
  minute <= 9 ? minute = '0' + minute : null;
  second <= 9 ? second = '0' + second : null;
  return {day,hour,minute,second}
}

/* 判断数据类型 */
const isDataType = {
	isArray:(obj) => {
	  return (typeof obj == 'object') && obj.constructor == Array;
	},
	isObject:(obj) => {
	  return Object.prototype.toString.call(obj) === "[object Object]";
	},
	isEmptyObject:(obj) => {
	  let t;
	  for (t in obj) return !1;
	  return !0
	}
}
// 数组排序
const arraySort = (arryObj)=> {
	//此为升序，若需降序请自行修改代码if条件大于改为小于
	let tmp;
	for(let i = 0;i<arryObj.length;i++){
		for(let j = 0;j<arryObj.length;j++){
			if(arryObj[j]>arryObj[j+1]){
				tmp = arryObj[j];
				arryObj[j] = arryObj[j+1];
				arryObj[j+1] = tmp;
			}
		}
	}
	return arryObj;
}

// 数组去重
const arrayRemoval = (arrayObj) => {
	let tmpArray = [];
	for(let i = 0;i<arrayObj.length;i++){
		if(tmpArray.indexOf(arrayObj[i]) == -1){
			tmpArray.push(arrayObj[i]);
		}
	}
	return tmpArray;
}

//数组筛选过滤
const arrayFilter = (arrayObj,keyValue) => {
	let tmpArray = [];
	for(let i = 0;i<arrayObj.length;i++){
		if(arrayObj[i].toString().indexOf(keyValue) != -1){
			tmpArray.push(arrayObj[i]);
		}
	}
	return tmpArray;
}
//数组对象指定属性过滤
const arrayObjFilter = (arrayObj,keyAttributeArray,keyValue) => {
	// 在vue文件中 import { enumeration } from '@/js_sdk/common.js'
	// 使用列子：
	// let arry = [{
	// 	name:"dsa",
	// 	key:"152"
	// 	},{
	// 		name:"ooo",
	// 		key:"sdf"
	// 	},{
	// 		name:123,
	// 		key:"wewe"
	// 	},{
	// 		name:"loe",
	// 		key:"uuwe"
	// 	}];
	//arrayObjFilter(arry,[""name","key"],"s");
	let tmpArray = [];
	for(let i = 0;i<arrayObj.length;i++){
		for(let j in arrayObj[i]){
			for(let l = 0;l<keyAttributeArray.length;l++){
				if(j == keyAttributeArray[l]){
					if(arrayObj[i][j].toString().indexOf(keyValue) != -1){
						tmpArray.push(arrayObj[i]);
					}
				}
			}
		}
	}
	return tmpArray;
	
}

// 金钱格式化,三位逗号
const formatMoney = (num)=>{
	let newNum = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	return newNum;
}

// 生成一定范围内随机数
const RandomNum = (min, max) => {
	let num = Math.floor(Math.random() * (max - min + 1)) + min;
	return num;
};

// 数组交集
const similarity = (arr1, arr2) => arr1.filter(v => arr2.includes(v));


//数组中某元素出现的次数
/**
 * @param { array } arr
 * @param {*} value
 */
const countOccurrences = (arr, value)=> {
    return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}

// 字符串去除空格
/**
 * @param { string } str 待处理字符串
 * @param  { number } status 去除空格状态 1-所有空格  2-前后空格  3-前空格 4-后空格 默认为1
 */
const removeBlank = (str, status = 1)=> {
    if (status && status !== 1 && status !== 2 && status !== 3 && status !== 4) return;
    switch (status) {
        case 1:
            return str.replace(/\s/g, "");
        case 2:
            return str.replace(/(^\s)|(\s*$)/g, "");
        case 3:
            return str.replace(/(^\s)/g, "");
        case 4:
            return str.replace(/(\s$)/g, "");
        default:
            return str;
    }
}

//字体大小写转换
/**
 * @param { string } str 待转换的字符串
 * @param { number } type 1-全大写 2-全小写 3-首字母大写 其他-不转换
 */

const turnCase = (str, type)=> {
    switch (type) {
        case 1:
            return str.toUpperCase();
        case 2:
            return str.toLowerCase();
        case 3:
            return str[0].toUpperCase() + str.substr(1).toLowerCase();
        default:
            return str;
    }
}

// 数字超过规定大小加上加号“+”，如数字超过99显示99+
/**
 * @param { number } val 输入的数字
 * @param { number } maxNum 数字规定界限
 */
const numberDefine = (val, maxNum) =>{
    val = val ? val-0 :0;
    if (val > maxNum ) {
        return `${maxNum}+`
    }else{
        return val;
    }
};

